<template>
    <div style="padding: 50px;">
        <h2>摄像头列表:</h2>
        <select v-model="selectedCamera" @change="startCamera">
            <option v-for="camera in cameras" :key="camera.deviceId" :value="camera.deviceId">
                {{ camera.label }}
            </option>
        </select>
        <button @click="closeCamera">关闭摄像头</button>
        <h2>麦克风列表:</h2>
        <select v-model="selectedMicrophone" @change="startMicrophone">
            <option v-for="microphone in microphones" :key="microphone.deviceId" :value="microphone.deviceId">
                {{ microphone.label }}
            </option>
        </select>
        <button @click="closeMicrophne">关闭麦克风</button>
    </div>
    <div style="padding: 50px;">
        <!-- 展示获取的视频源 -->
        <video ref="video" autoplay style="width: 180px;height: 180px;" controls></video>
        <!-- 展示获取的音频源 -->
        <audio ref="audio" autoplay controls></audio>
    </div>
</template>
  
<script>
export default {
    data() {
        return {
            cameras: [],
            microphones: [],
            selectedCamera: null,
            selectedMicrophone: null,
            cameraStream: null,
            microphoneStream: null,
        };
    },
    created() {
        this.initDevice()
    },
    methods: {
        async initDevice () {
            let this_ = this
            // 检查浏览器是否支持getUserMedia方法
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                // 请求访问相机设备
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(async function(stream) {
                    // 相机访问成功，做后续操作
                    this_.InputDeviceInfo()
                })
                .catch(function(error) {
                    if (error.name === 'NotAllowedError' || error.name === 'NotFoundError') {
                        // 用户未授权相机访问或者没有可用设备
                        alert('请允许访问相机并确保设备已连接');
                    } else {
                        // 其他错误
                        alert('启动相机时出错：' + error.message);
                    }
                    });
            } else {
                // 浏览器不支持getUserMedia方法
                alert('您的浏览器不支持该功能，请更换浏览器或升级至最新版本');
            }
            
        },

        async InputDeviceInfo () {
            try {
                const devices = await navigator.mediaDevices.enumerateDevices();
                this.cameras = devices.filter((device) => device.kind === 'videoinput');
                this.microphones = devices.filter((device) => device.kind === 'audioinput');
            } catch (error) {
                console.error('无法获取设备列表:', error);
            }
        },

        async startCamera() {
            if (this.selectedCamera) {
                try {
                    this.cameraStream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: this.selectedCamera } });
                    this.$refs.video.srcObject = this.cameraStream;
                } catch (error) {
                    console.error('无法启动摄像头:', error);
                }
            }
        },
        async startMicrophone() {
            if (this.selectedMicrophone) {
                try {
                    this.microphoneStream = await navigator.mediaDevices.getUserMedia({ audio: { deviceId: this.selectedMicrophone } });
                    this.$refs.audio.srcObject = this.microphoneStream;
                } catch (error) {
                    console.error('无法启动麦克风:', error);
                }
            }
        },
        closeCamera() {
            if (this.cameraStream) {
                this.cameraStream.getTracks().forEach((track) => {
                    track.stop();
                });
                this.$refs.video.srcObject = null;
                this.cameraStream = null;
                this.selectedCamera = null
                this.cameras = []
            }
            // this.initDevice()
        },
        closeMicrophne() {
            if (this.microphoneStream) {
                this.microphoneStream.getTracks().forEach((track) => {
                    track.stop();
                });
                this.$refs.audio.srcObject = null;
                this.microphoneStream = null;
                this.microphones = []
                this.selectedMicrophone = null
            }
            this.initDevice()
        }
    },
};
</script>
  